<template>
  <pc-nav></pc-nav>
  <!-- <bread></bread> -->
  <div class="container">
  <s-layout title="确认订单">
    <view class="header-text">订单确认</view>
    <view
      class="bg-white address-box ss-m-b-14 ss-r-b-20"
      @tap="onSelectAddress"
      v-if="state.orderInfo.need_address === 1"
    >
      <s-address-item :item="state.addressInfo" :hasBorderBottom="false">
        <view class="ss-rest-button"><text class="_icon-forward"></text></view>
      </s-address-item>
    </view>
    <view class="sub-header-text">在线课程</view>
    <view class="goods-list-header">
      <view class="goods-list-header-item img">图片</view>
      <view class="goods-list-header-item name">产品名称</view>
      <view class="goods-list-header-item price">单价</view>
      <view class="goods-list-header-item num">数量</view>
      <view class="goods-list-header-item total">总计</view>
    </view>
    <view class="order-card-box ss-m-b-14">
      <s-order-confirm-goods-item-pc
        v-for="item in state.orderInfo.goods_list"
        :key="item.goods_id"
        :img="item.current_sku_price.image || item.goods.image"
        :title="item.goods.title"
        :skuText="item.current_sku_price?.goods_sku_text"
        :price="item.current_sku_price.price"
        :num="item.goods_num"
        marginBottom="10"
      >
      </s-order-confirm-goods-item-pc>

      <view style="margin: 10px auto;font-size:14px">
        说明：支付成功后自动开通，可在【个人中心】查看
      </view>
    </view>

    <view class="order-item  ss-col-center bg-white ss-r-20 ss-m-t-30" style="height:100px">
      <view class="item-title">订单备注</view>
      <view class="ss-flex ss-col-center" style="width:450px;">
        <uni-easyinput
          maxlength="100"
          placeholder="备注信息"
          v-model="state.orderPayload.remark"
          :inputBorder="true"
          :clearable="true"
        ></uni-easyinput>
      </view>
    </view>

    <!-- 合计 -->
    <view class="bg-white total-card-box ss-m-b-14 ss-r-20">
      <view class="total-box-content">
        <!-- <view class="order-item ss-flex ss-col-center">
          <view class="item-title">商品金额</view>
          <view class="ss-flex-1"></view>
          <view class="ss-flex ss-col-center">
            <text class="item-value">￥{{ state.orderInfo.goods_amount }}</text>
          </view>
        </view> -->
        <!-- <view
          class="order-item ss-flex ss-col-center"
          v-if="state.orderPayload.order_type === 'score'"
        >
          <view class="item-title">扣除积分</view>
          <view class="ss-flex-1"></view>
          <view class="ss-flex ss-col-center">
            <image
              :src="sheep.$url.static('/assets/addons/shopro/uniapp/goods/score1.svg')"
              class="score-img"
            ></image>
            <text class="item-value">{{ state.orderInfo.score_amount }}</text>
          </view>
        </view> -->
        <!-- <view class="order-item ss-flex ss-col-center ss-row-between">
          <view class="item-title">运费</view>
          <view class="ss-flex ss-col-center">
            <text class="item-value ss-m-r-24">+￥{{ state.orderInfo.dispatch_amount }}</text>
          </view>
        </view> -->
		
        <view
          class="order-item ss-flex ss-col-center"
          v-if="state.orderInfo.promo_infos?.length"
        >
          <!-- <view v-if="state.orderInfo.promo_discount_fee > 0" class="order-item ss-flex ss-col-center ss-row-between"> -->
          <view class="item-title">平台优惠</view>
          <view class="ss-flex-1"></view>
          <view class="ss-flex ss-col-center" @tap="state.showDiscount = true">
            <text class="item-value text-red"> -￥{{ state.orderInfo.promo_discount_fee }} </text>
            <text class="_icon-forward item-icon"></text>
          </view>
        </view>

        <view v-if="state.orderPayload.order_type != 'score'">
          <view class="order-item ss-flex ss-col-center">
            <view class="sub-header-text">优惠券</view>
            <view class="ss-flex-1"></view>
            <view class="ss-flex ss-col-center">
              <text class="item-value text-red" v-if="state.orderPayload.coupon_id"
                >-￥{{ state.orderInfo.coupon_discount_fee }}</text
              >
              <text
                class="item-value" style="font-size:20px;"
                :class="state.couponInfo.can_use?.length > 0 ? 'text-red' : 'text-disabled'"
                v-else
                >{{
                  state.couponInfo.can_use?.length > 0
                    ? state.couponInfo.can_use?.length + '张可用，请选择使用'
                    : '暂无可用优惠券'
                }}</text
              >
            </view>
          </view>
          <view class="coupon-list-wrapper">
            <view v-for="(item, index) in state.couponInfo.can_use" :key="index">
              <view class="coupon-item-wrapper" @click="onSelectCoupon(item.id)">
                <s-coupon-list-pc :data="item" type="user" :disabled="false" class="coupon-item">
                  <template #default>
                    <span style="color:#ec0b0b;font-size:14px;">选择: </span><radio
                      color="var(--ui-BG-Main)"
                      style="transform: scale(0.8)"
                      @click="onSelectCoupon(item.id)"
                      :checked="state.orderPayload.coupon_id === item.id"
                    />
                  </template>
                </s-coupon-list-pc>
              </view>
            </view>
          </view>
        </view>

		
        <view v-if="state.orderPayload.order_type != 'score' && state.couponInfo2.can_use?.length > 0">
          <view class="order-item ss-flex ss-col-center">
            <!-- <view v-if="state.orderInfo.coupon_discount_fee > 0" class="order-item ss-flex ss-col-center ss-row-between"> -->
            <view class="sub-header-text">内部优惠</view>
            <view class="ss-flex-1"></view>
            <view class="ss-flex ss-col-center" @tap="state.showCoupon2 = true">
              <text class="item-value text-red" v-if="state.orderPayload.coupon_id2"
                >-￥{{ state.orderInfo.coupon_discount_fee2 }}</text
              >
              <text
                class="item-value"
                :class="state.couponInfo2.can_use?.length > 0 ? 'text-red' : 'text-disabled'"
                v-else
                >{{
                  state.couponInfo2.can_use?.length > 0
                    ? state.couponInfo2.can_use?.length + '张可用'
                    : '暂无可用优惠券'
                }}</text
              >

              <text class="_icon-forward item-icon"></text>
            </view>
          </view>
          <view class="coupon-list-wrapper">
            <view v-for="(item, index) in state.couponInfo2.can_use" :key="index">
              <view class="coupon-item-wrapper" @click="onSelectCoupon2(item.id)">
                <s-coupon-list-pc :data="item" type="user" :disabled="false" class="coupon-item">
                  <template #default>
                    <radio
                      color="var(--ui-BG-Main)"
                      style="transform: scale(0.8)"
                      :checked="state.orderPayload.coupon_id2 === item.id"
                    />
                  </template>
                </s-coupon-list-pc>
              </view>
            </view>
          </view>
        </view>

        <view
          class="order-item ss-flex ss-col-center ss-m-t-30"
          v-if="state.orderPayload.order_type != 'score'"
        >
          <!-- <view v-if="state.orderInfo.coupon_discount_fee > 0" class="order-item ss-flex ss-col-center ss-row-between"> -->
          <view class="sub-header-text yaoqingma-title">
            邀请码：
            <input
              class="yaoqingma-input-box"
              type="text"
              value=""
              placeholder="请输入邀请码"
              v-model="state.yqmcode"

            />
            <view class="yaoqingma-exchange ss-reset-button ui-BG-Main-Gradient ui-Shadow-Main" @tap="onyanzhengyqmcode">兑换</view>
          </view>
          <view class="ss-flex-1"></view>
          <view class="ss-flex ss-col-center">
            <text class="item-value text-red" v-if="state.orderPayload.yqmcode"
              >-￥{{ state.orderInfo.yqm_discount_fee }}</text
            >
          </view>
        </view>
        <view style="height: 100rpx"></view>
      </view>
    </view>

    <view style="height:120px;"></view>
    <!-- 满额折扣弹框  -->
    <s-discount-list
      type="center"
      v-model="state.orderInfo"
      :show="state.showDiscount"
      @close="state.showDiscount = false"
    />
    <!-- 底部 -->
    <view class="footer-box border-top ss-flex ss-row-right ss-p-x-20 ss-col-center">
      <view class="total-box-footer ss-flex ss-col-center ss-m-r-30">
        <view class="total-num ss-font-30 text-red"> ￥{{ state.orderInfo.pay_fee }} </view>
        <view v-if="state.orderPayload.order_type === 'score'" class="ss-flex">
          <view class="total-num ss-font-30 text-red ss-m-l-4">+</view>
          <image
            :src="sheep.$url.static('/assets/addons/shopro/uniapp/goods/score1.svg')"
            class="score-img"
          ></image>
          <view class="total-num ss-font-30 text-red">{{ state.orderInfo.score_amount }}</view>
        </view>
      </view>

      <button
        class="ss-reset-button ui-BG-Main-Gradient submit-btn ui-Shadow-Main"
        @tap="onConfirm"
      >
        {{ exchangeNow ? '立即兑换' : '提交订单' }}
      </button>
    </view>
  </s-layout>
  </div>
</template>

<script setup>
  import { ref, reactive, computed } from 'vue';
  import { onLoad, onPageScroll, onShow } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import { isEmpty } from 'lodash';
  import pcNav from '@/sheep/components/pc-nav/pc-nav.vue';
  import Bread from '@/sheep/components/bread/bread.vue';
  import SuPopup from '@/sheep/ui/su-popup/su-popup.vue';
  import SLayout from '@/sheep/components/s-layout/s-layout.vue';
  import {
    showAuthModal,
    closeAuthModal
  } from '@/sheep/hooks/useModal';
  const state = reactive({
    orderPayload: {
      yqmcode:''
    },
    orderInfo: {},
    addressInfo: {},
    invoiceInfo: {},
    totalNumber: 0,
    showCoupon: false,
    showCoupon2: false,
    couponInfo: [],
    couponInfo2: [],
    showDiscount: false,
    yqmcode: ''
  });

  // 立即兑换(立即兑换无需跳转收银台)
  const exchangeNow = computed(
    () => state.orderPayload.order_type === 'score' && state.orderInfo.pay_fee == 0,
  );





  // 选择地址
  function onSelectAddress() {
    uni.$once('SELECT_ADDRESS', (e) => {
      changeConsignee(e.addressInfo);
    });
    sheep.$router.go('/pages/user/address/list');
  }

  // 更改收货人地址&计算订单信息
  async function changeConsignee(addressInfo = {}) {
    if (isEmpty(addressInfo)) {
      const { code, data } = await sheep.$api.user.address.default();
      if (code === 1 && !isEmpty(data)) {
        addressInfo = data;
      }
    }
    if (!isEmpty(addressInfo)) {
      state.addressInfo = addressInfo;
      state.orderPayload.address_id = state.addressInfo.id;
    }
    getOrderInfo();
  }

  // 选择优惠券
  async function onSelectCoupon(e) {
    state.orderPayload.coupon_id = e === state.orderPayload.coupon_id ? 0 : e;
    getOrderInfo();
    state.showCoupon = false;
  }

  async function onSelectCoupon2(e) {
    state.orderPayload.coupon_id2 = e === state.orderPayload.coupon_id2 ? 0 : 0;
    getOrderInfo();
    state.showCoupon2 = false;
  }


  async function onyanzhengyqmcode() {
      state.orderPayload.yqmcode = state.yqmcode;
      getOrderInfo();
  }

  // 选择发票信息
  function onSelectInvoice() {
    uni.$once('SELECT_INVOICE', (e) => {
      state.invoiceInfo = e.invoiceInfo;
      state.orderPayload.invoice_id = e.invoiceInfo.id || 0;
    });
    sheep.$router.go('/pages/user/invoice/list');
  }

  // 提交订单/立即兑换
  function onConfirm() {
    state.orderPayload.yqmcode = state.yqmcode;
    if (!state.orderPayload.address_id && state.orderInfo.need_address === 1) {
      sheep.$helper.toast('请选择收货地址');
      return;
    }
    sheep.$store('user').getInfo()
      .then((resinfo) => {
        /*if (1) {*/
        if (resinfo.mobile) {
    if (exchangeNow.value) {
      uni.showModal({
        title: '提示',
		content: '确定使用积分立即兑换?',
        cancelText: '再想想',
        success: async function (res) {
          if (res.confirm) {
            submitOrder();
          }
        },
      });
    } else {
		
		uni.showModal({
		  title: '购买提示',
		  showCancel:false,
		  content: '1、计划社微课程退费规则:计划社微课程平台网络课程为有版权保护的虚拟产品。\n' +
        '2、学员在购买开通网络课程7日之内，没有学习网络课程主动放弃学习的，可以无条件退还全部网络课程费用(试卷、资料、文档、题库等产品除外)。\n' +
        '3、已经购买开通网络课程超过7天的，如因特殊原因申请退款，根据平台记录的学习情况按实际学习进度比例进行退款。\n' +
        '4、开通超过30天申请退款的，根据平台记录的学习情况按实际学习进度比例进行退款但可申请退款比例最多不超过50%。\n' +
        '5、开通超过6个月的，不支持任何形式的退款申请。\n' +
        '6、退费金额在学员与出版社达成一致后，出版社在15个工作日内将相应退费款项按原渠道退还给学员。',
		  confirmText: '已知晓',
		  success: async function (res) {
		    if (res.confirm) {
		      submitOrder();
		    }
		  },
		});
      //submitOrder();
    }
  } else {
    sheep.$store('modal').$patch((state) => {
      state.auth = '';
      setTimeout(() => {
        showAuthModal('changeMobile');
      }, 100);

    });

  }
  })
  }

  // 创建订单&跳转
  async function submitOrder() {
    const { code, data } = await sheep.$api.order.create(state.orderPayload);
    if (code === 1) {
      // 更新购物车列表
      if (state.orderPayload.from === 'cart') {
        sheep.$store('cart').submitUpdateList();
      }
      if (data.status === 'paid') {
        sheep.$router.redirect('/pages/pay/result', {
          orderSN: data.order_sn,
        });
      } else {
        sheep.$router.redirect('/pages/pay/index', {
          orderSN: data.order_sn,
        });
      }
    }
  }

  // 检查库存&计算订单价格
  async function getOrderInfo() {
    let { code, data } = await sheep.$api.order.calc(state.orderPayload);
    if (code === 1) {
      state.totalNumber = 0;
      state.orderInfo = data;
      state.orderInfo.goods_list.forEach((item) => {
        state.totalNumber += item.goods_num;
      });
    }
  }

  // 获取可用优惠券
  async function getCoupons() {
    const { code, data } = await sheep.$api.order.coupons(state.orderPayload);
    if (code === 1) {
      state.couponInfo = data;
    }
  }

  async function getCoupons2() {
    const { code, data } = await sheep.$api.order.coupons2(state.orderPayload);
    if (code === 1) {
      state.couponInfo2 = data;
    }
  }

  onLoad(async (options) => {
	  //console.log('options');
	  //console.log(options);
	if(options.ddyqm)
	{
		//console.log(options.ddyqm);
		let yaoqingmas={}
		yaoqingmas.yqm=options.ddyqm;
		//console.log(yaoqingmas);
		const { code, data } = await sheep.$api.order.yaoqingmalistcheck(yaoqingmas);
		//alert(code)
		if(code===1)
		{
			//console.log(data.goodsinfo);
			var goods_list = JSON.parse(data.goodsinfo);
			//console.log(goods_list);
			//state.orderPayload.order_type= 'goods';
			
			sheep.$router.go('/pages/order/confirm', {
			  data: JSON.stringify({
			    order_type: 'goods',
			    goods_list,
			    from: 'cart',
				yqmcode:yaoqingmas.yqm
			  }),
			});
		}
	}
    if (options.data) {
		//alert(3);
      state.orderPayload = JSON.parse(options.data);
      changeConsignee();
      if (state.orderPayload.order_type !== 'score') {
        getCoupons();
        getCoupons2();
      }
    }
  });
</script>

<style lang="scss" scoped>
  :deep() {
    .page-app {
      height: auto;
    }
    .page-app .page-body {
      background: #fff !important;
    }

    .uni-input-wrapper {
      width: 100%;
    }

    .uni-easyinput__content-input {
      font-size: 28rpx;
      height: 72rpx;
      padding-right: 0 !important;
      margin-left: 10px;

      .uni-input-input {
        font-weight: 500;
        color: #333333;
        font-size: 26rpx;
        height: 32rpx;
        margin-top: 4rpx;
      }
    }
    .uni-easyinput__content {
      display: flex !important;
      align-items: center !important;
      justify-content: right !important;
    }
  }

  .score-img {
    width: 36rpx;
    height: 36rpx;
    margin: 0 4rpx;
  }
  .order-item {
    height: 80rpx;

    .item-title {
      font-size: 28rpx;
      font-weight: 400;
    }

    .item-value {
      font-size: 28rpx;
      font-weight: 500;
      font-family: OPPOSANS;
    }

    .text-disabled {
      color: #bbbbbb;
    }

    .item-icon {
      color: $dark-9;
    }

    .remark-input {
      text-align: right;
    }

    .item-placeholder {
      color: $dark-9;
      font-size: 26rpx;
      text-align: right;
    }
  }

  .total-box-footer {
    height: 90rpx;

    .total-num {
      color: #333333;
      font-family: OPPOSANS;
    }
  }

  .footer-box {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    height: 200rpx;
    width: 1200px;
    margin: 0 auto;
    background: white;

    .submit-btn {
      width: 240rpx;
      height: 70rpx;
      font-size: 28rpx;
      font-weight: 500;

      .goto-pay-text {
        line-height: 28rpx;
      }
    }

    .cancel-btn {
      width: 240rpx;
      height: 80rpx;
      font-size: 26rpx;
      background-color: #e5e5e5;
      color: $dark-9;
    }
  }
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
  }
  .subtitle {
    font-size: 28rpx;
    color: #999999;
  }
  .cicon-checkbox {
    font-size: 36rpx;
    color: var(--ui-BG-Main);
  }
  .cicon-box {
    font-size: 36rpx;
    color: #999999;
  }
  .title-text{
    font-size: 44rpx;
  }
  .yaoqingma-title{
    display: flex;
    align-items: center;
    gap: 10px;
  }
  .yaoqingma-input-box {
    height: 60rpx;
    border-radius: 10rpx;
    padding: 10rpx 20rpx;
    border: solid 1px #999999;
  }
  .yaoqingma-exchange{
    cursor: pointer;
    height: 60rpx;
    width: 80px;
    border-radius: 10rpx;
    padding: 10rpx 20rpx;
    color: #999999;
    font-weight: normal;
  }

  .header-text{
    font-size: 20px;
    color: #222;
    font-weight: bold;
    margin-bottom: 20px;
  }
  .sub-header-text {
    display: flex;
    align-items: center;
    font-size: 16px;
    color: #222;
    font-weight: bold;

    &::before{
      content: '';
      display: block;
      width: 2px;
      height: 10px;
      background: #ff6000;
      margin-right: 10px;
    }

    &.yaoqingma-title::before {
      margin-right: 0;
    }
  }
  .goods-list-header{
    margin: 10px 0;
    display: flex;
    align-items: center;
    line-height: 40px;
    border-bottom: 1px solid #ebebeb;
    color: #444;
    background: #f4f4f4;

    .goods-list-header-item{
      text-align: center;
      font-size: 14px;
      color: #222;
      flex-shrink: 0;

      &:not(:last-child) {
        border-right: 1px solid #ebebeb;
      }

      &.name {
        flex-grow: 1;
      }

      &.img {
        width: 162px;
      }
      &.price {
        width: 134px;
      }
      &.num {
        width: 161px;
      }
      &.total {
        width: 119px;
      }
    }
  }

  .coupon-list-wrapper {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    padding: 0 10px;
  }

  .coupon-item-wrapper {
    width: 260px;
    background-color: #f4f4f4;
    border-radius: 10px;
    padding: 10px;

    .coupon-item-text {
      font-size: 12px;
      color: #999;
      margin-bottom: 5px;
    }

    > .coupon-item {
      margin: 0;
    }
  }
  ::v-deep .uni-modal{
    max-width: 800px;
    width: 800px;
    text-align: left;
  }
  ::v-deep .uni-modal__ft{
    text-align: center;
  }
  ::v-deep .uni-modal__hd{
    text-align: center;
  }
  ::v-deep .uni-modal__bd{
    line-height: 28px;
  }
  ::v-deep .uni-radio-input{
    width:24px;
    height:24px;
    border: 1px solid #ec0b0b;
  }
</style>
